import { ref } from 'vue'
import { handleError } from '@/utils/handleError'

export function useCanvasPersist(canvas) {
    const isSaving = ref(false)

    const saveToLocal = async () => {
        if (!canvas || isSaving.value) return
        isSaving.value = true
        try {
            const canvasJson = canvas.toJSON(['id', 'selectable', 'deviceInfo'])

            const canvasProps = {
                width: canvas.width,
                height: canvas.height,
                zoom: canvas.getZoom(),
                viewportTransform: canvas.viewportTransform
            }

            const saveData = {
                version: '1.0',
                timestamp: new Date().toISOString(),
                canvas: canvasJson,
                properties: canvasProps
            }

            const saveString = JSON.stringify(saveData)
            window.localStorage.setItem('canvas_data', saveString)
        } catch (error) {
            handleError(error, '保存失败：')
        } finally {
            isSaving.value = false
        }
    }

    const loadFromLocal = async () => {
        try {
            const savedData = window.localStorage.getItem('canvas_data')
            if (!savedData) {
                console.log('No saved data found')
                return false
            }

            const data = JSON.parse(savedData)
            if (data.properties) {
                canvas.setWidth(data.properties.width)
                canvas.setHeight(data.properties.height)
                canvas.setZoom(data.properties.zoom)
                if (data.properties.viewportTransform) {
                    canvas.setViewportTransform(data.properties.viewportTransform)
                }
            }

            return new Promise((resolve) => {
                canvas.loadFromJSON(data.canvas, () => {
                    canvas.getObjects().forEach(obj => {
                        if (obj.deviceInfo) {
                            obj.deviceInfo = obj.deviceInfo
                        }
                        if (obj instanceof fabric.Line) {
                            obj.selectable = true;
                        }
                    })
                    canvas.renderAll()
                    resolve(true)
                })
            })
        } catch (error) {
            console.error('Load error:', error)
            ElMessage.error('加载失败：' + error.message)
            return false
        }
    }

    const saveWithConfirm = () => {
        ElMessageBox.confirm(
            '确定要保存当前画布？这将覆盖之前保存的内容。',
            '保存确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(() => {
                saveToLocal()
                ElMessage.success('保存成功')
                return true
            })
            .catch(() => {
                return false
            })
    }

    let autoSaveTimer = null

    const startAutoSave = (interval = 60 * 1000) => {
        stopAutoSave()
        autoSaveTimer = setInterval(saveToLocal, interval)
    }

    const stopAutoSave = () => {
        if (autoSaveTimer) {
            clearInterval(autoSaveTimer)
            autoSaveTimer = null
        }
    }

    const cancelEdit = async () => {
        const result = await loadFromLocal()
        if (result) {
            ElMessage.info('已恢复到上次保存的状态')
        }
    }

    return {
        saveToLocal,
        loadFromLocal,
        saveWithConfirm,
        startAutoSave,
        stopAutoSave,
        cancelEdit,
    }
}